import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import path from 'path'

// Custom APIs for renderer
const api = {
  path: {
    join: (...args) => path.join(__dirname, ...args)
  },
  minimize: () => ipcRenderer.invoke('window:minimize'),
  maximize: () => ipcRenderer.invoke('window:maximize'),
  close: (e) => ipcRenderer.invoke('window:close', e),
  resize: (direction) => ipcRenderer.invoke('window:resize', direction),
  openDirectoryDialog: () => ipcRenderer.invoke('open-directory-dialog'),
  scanAudioFiles: (dirPath) => ipcRenderer.invoke('scan-audio-files', dirPath),
  getFileBufByFilePath: (filePath) => ipcRenderer.invoke('get-file-buf', filePath),
  getFileDataByFilePath: (filePath) => ipcRenderer.invoke('get-file-data', filePath),
  getMacAddress: (filePath) => ipcRenderer.invoke('get-mac-address', filePath),
  requestProxy: (requestConfig) => ipcRenderer.invoke('request-proxy', requestConfig)
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electronAPI', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electronAPI = electronAPI
  window.api = api
}
